//
//  RBLuckyDrawVC.m
//  zhongzhenglu
//
//  Created by XL on 2022/8/29.
//

#import "RBLuckyDrawVC.h"
#import "RBDefine.h"
#import "UIView+RBAdd.h"
#import "UIScrollView+RBAdd.h"
#import "RBSearchTagView.h"
#import "RBThemeConfig.h"
#import <Masonry.h>
#import "RBNavigationBar.h"
#import "RBTextField.h"
#import "UIButton+RBAdd.h"
#import <UIColor+YYAdd.h>
#import <UINavigationController+FDFullscreenPopGesture.h>
#import "RBLuckyGoodModel.h"
#import "RBTimer.h"
#import "RBGradientView.h"
#import "RBLuckyDrawHistoryVC.h"
#import "RBLuckyDrawPopVC.h"
#import "RBLuckyDrawResponse.h"
#import "UIViewController+RBAdd.h"
#import "RBRegularWebView.h"
#import "RBLuckyDrawResultResponse.h"

@interface RBLuckyDrawVC ()

@property(nonatomic, strong)RBNavigationBar *navigationBar;
@property(nonatomic, strong)UIScrollView *scrollView;

@property(nonatomic, strong) UILabel *rollCountL;

@property(nonatomic, strong)NSArray *luckyGoods;
@property(nonatomic, strong)NSMutableArray *luckyGoodViews;
//掷点中
@property(nonatomic, assign)BOOL rolling;
//当前掷点位置
@property(nonatomic, assign)NSInteger rollIndex;
//目标掷点位置
@property(nonatomic, assign) NSInteger desIndex;
//伪动画过程还需经过目标掷点位置几次
@property(nonatomic, assign) NSInteger needPassCount;
@property(nonatomic, strong)RBTimer *timer;

@property(nonatomic, strong) RBLuckyDrawResponse *response;



@end

@implementation RBLuckyDrawVC

#pragma mark - Lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self setup];
    [self getData];
}

#pragma mark - Private

- (void)setup
{
    self.fd_prefersNavigationBarHidden = YES;
    self.view.backgroundColor = UIColor.whiteColor;
    [self.view view_addView:({
        UIImageView *view = [RanTool imgViewWithMode:2 radius:0 imgName:@"luckyDrawBg"];
        view.backgroundColor = [UIColor colorWithHexString:@"#BBD0F8"];
        view;
    }) withHeight:CGFLOAT_MIN width:CGFLOAT_MIN top:0 bottom:0 left:0 right:0 centerX:0];
    self.scrollView.hidden = NO;
    self.navigationBar.hidden = NO;
}

- (void)fillData
{
    if(self.response.jiang_list.count != 8)
    {
        [self.view showTip:@"数据错误,请稍后重试" completion:nil];
        return;
    }
    
    NSArray *displayIndexArray = @[@0,@1,@2,@5,@8,@7,@6,@3,@4];
    for (NSInteger i = 0; i < self.response.jiang_list.count; i++)
    {
        RBLuckyGoodModel *model = self.response.jiang_list[i];
        model.displayIndex = [displayIndexArray[i] intValue];
        model.randomIndex = i;
    }
    self.luckyGoods = ({
        NSMutableArray *arrayM = NSMutableArray.array;
        [arrayM addObjectsFromArray:self.response.jiang_list];
        [arrayM addObject:({
            RBLuckyGoodModel *model = RBLuckyGoodModel.new;
            model.title = @"";
            model.displayIndex = 4;
            model.randomIndex = -1;
            model;
        })];
        arrayM;
    });
    
    [self.scrollView rbSetContentWidth:kRBMainScreenWidth];
    [self.scrollView addView:[RanTool imgViewWithMode:1 radius:0 imgName:@"luckDrawTopLogo.png"] withHeight:Zoom(180) width:kRBMainScreenWidth top:Zoom(20) bottom:0 left:0 right:0 centerX:0];
    [self.scrollView addView:({
        UIView *view = UIView.new;
        [view h_view_addView:({
            UILabel *view = [RanTool labelWithFontSize:Zoom(13) weight:0 color:@"253555" align:1 text:@"" bgColor:@"#DDE9FF" radius:Zoom(19)];
            self.rollCountL = view;
            [self reloadRollCount];
            view;
        }) withHeight:CGFLOAT_MIN width:Zoom(153) top:0 bottom:0 left:0 right:CGFLOAT_MIN centerY:0];
        [view h_view_addView:[RanTool labelWithFontSize:Zoom(13) weight:0 color:@"253555" align:1 text:[NSString stringWithFormat:@"每次消耗金币：%@", self.response.jiang_guize.xiaohao] bgColor:@"#DDE9FF" radius:Zoom(19)] withHeight:CGFLOAT_MIN width:Zoom(153) top:0 bottom:0 left:Zoom(12) right:CGFLOAT_MIN centerY:0];
        view;
    }) withHeight:Zoom(38) width:CGFLOAT_MIN top:Zoom(20) bottom:0 left:Zoom(32) right:Zoom(25) centerX:0];
    
    [self.scrollView addView:({
        UIImageView *view = [RanTool imgViewWithMode:0 radius:0 imgName:@"luckyDrawBox"];
        view.userInteractionEnabled = YES;
        
        CGFloat itemW = Zoom(88);
        CGFloat itemH = Zoom(87);
        for (RBLuckyGoodModel *model in self.luckyGoods)
        {
            CGFloat x = Zoom(15) + model.displayIndex%3 * (itemW + Zoom(4));
            CGFloat y = Zoom(15) + model.displayIndex/3 * (itemH + Zoom(4));
            if (model.randomIndex >= 0)
            {
                UIView *itemView = [self goodsItemWithImg:model.picurl name:model.title];
                itemView.tag = model.randomIndex;
                [view addSubview:itemView];
                itemView.frame = CGRectMake(x, y, itemW, itemH);
                [self.luckyGoodViews addObject:itemView];
            }
            else
            {
                UIImageView *itemView = [RanTool imgViewWithMode:0 radius:0 imgName:@"luckDrawStart.png"];
                [itemView rbAddTapGesWithTarget:self action:@selector(rollBtnTapped)];
                [view addSubview:itemView];
                itemView.frame = CGRectMake(x, y, itemW, itemH);
            }
        }
        
        view;
    }) withHeight:Zoom(304) width:Zoom(302) top:Zoom(40) bottom:CGFLOAT_MIN left:CGFLOAT_MIN right:CGFLOAT_MIN centerX:YES];
    
    [self.scrollView addView:({
        UIView *view = UIView.new;
        view.backgroundColor = [UIColor colorWithHexString:@"#DFEAFF"];
        [view rbSetCornerRadius:Zoom(10)];
        [view view_addView:[RanTool labelWithFontSize:Zoom(18) weight:1 color:[RBThemeConfig textBlackColor] align:0 text:self.response.jiang_guize.title] withHeight:CGFLOAT_MIN width:CGFLOAT_MIN top:Zoom(35) bottom:0 left:Zoom(19) right:0 centerX:0];
        
        RBRegularWebView *webView = RBRegularWebView.new;
        webView.preferStyle = @"font-size:14px;line-height:22px;color:#333333;";
        [view view_addView:webView withHeight:Zoom(30) width:CGFLOAT_MIN top:Zoom(28) bottom:Zoom(46) left:Zoom(20) right:Zoom(20) centerX:0];
        [webView setHtmlString:self.response.jiang_guize.content];
        
        view;
    }) withHeight:CGFLOAT_MIN width:CGFLOAT_MIN top:Zoom(39) bottom:0 left:Zoom(13) right:Zoom(13) centerX:0];
    
    [self.scrollView addView:[RanTool labelWithFontSize:Zoom(14) weight:0 color:@"#2A364E" align:1 text:@"中正路（大连）网络科技有限公司"] withHeight:CGFLOAT_MIN width:CGFLOAT_MIN top:Zoom(25) bottom:Zoom(20) left:0 right:0 centerX:0];
}

- (void)reloadRollCount
{
    self.rollCountL.text = [NSString stringWithFormat:@"剩余抽奖次数：%zd", self.response.jiang_guize.mianfei];
}

#pragma mark - Network

- (void)getData
{
    __weak typeof(self) weak_self = self;
    [self viewLoadDataWithParam:^(NSMutableDictionary *dicM) {
        
    } path:@"hu_jiang_list" post:YES log:YES responseClass:RBLuckyDrawResponse.class desView:self.view showHud:YES showPlaceHolder:YES sucBlock:^(id data) {
        weak_self.response = data;
        [weak_self fillData];
    } failBlock:^(id data) {
        
    } reloadBlock:^{
        [weak_self getData];
    }];
}

#pragma mark - Event

- (void)rollBtnTapped
{
    if (self.rolling)
    {
        return;
    }
    self.rolling = YES;
    self.rollIndex = -1;
    self.desIndex = -1;
    self.needPassCount = 1;
    [self startRoll];
    
    __weak typeof(self) weak_self = self;
    [self viewLoadDataWithParam:^(NSMutableDictionary *dicM) {
        
    } path:@"hu_jiang_sub" post:YES log:YES responseClass:RBLuckyDrawResultResponse.class desView:self.view showHud:NO showPlaceHolder:NO sucBlock:^(RBLuckyDrawResultResponse *data) {
        for (RBLuckyGoodModel *model in weak_self.luckyGoods)
        {
            if([data.id isEqualToString:model.id])
            {
                weak_self.desIndex = model.randomIndex;
                break;
            }
        }
        if(weak_self.desIndex < 0)
        {
            weak_self.rolling = NO;
            weak_self.rollIndex = -1;
            [weak_self reloadGoodViews];
        }
        weak_self.response.jiang_guize.mianfei = MAX(0, weak_self.response.jiang_guize.mianfei - 1);
        [weak_self reloadRollCount];
    } failBlock:^(RBLuckyDrawResultResponse *data) {
        [weak_self.view showTip:data.message completion:nil];
        weak_self.rolling = NO;
        weak_self.rollIndex = -1;
        [weak_self reloadGoodViews];
    } reloadBlock:nil];
}

- (void)startRoll
{
    __weak typeof(self) weakSelf = self;
    [self.timer startTimerWithInterval:0.1 block:^(float countF, NSInteger countI) {
        if(!weakSelf.rolling)
        {
            [weakSelf.timer stop];
        }
        else if ((countF > 2.5 && weakSelf.desIndex >= 0))
        {
            [weakSelf.timer stop];
            [weakSelf countDown];
        }
        else
        {
            [weakSelf rollToNext];
        }
    }];
}

- (void)countDown
{
    __weak typeof(self) weakSelf = self;
    [self.timer startTimerWithInterval:0.3 block:^(float countF, NSInteger countI) {
        if (weakSelf.rollIndex == weakSelf.desIndex)
        {
            if(weakSelf.needPassCount <= 0)
            {
                [weakSelf.timer stop];
                weakSelf.rolling = NO;
                RBLuckyGoodModel *model = weakSelf.luckyGoods[weakSelf.desIndex];
                RBLuckyDrawPopVC *vc = RBLuckyDrawPopVC.new;
                vc.success = model.chi_id;
                vc.name = model.title;
                vc.oneMoreBlock = ^{
                    [weakSelf rollBtnTapped];
                };
                [weakSelf presentVc:vc];
            }
            else
            {
                weakSelf.needPassCount--;
                [weakSelf rollToNext];
            }
        }
        else
        {
            [weakSelf rollToNext];
        }
    }];
}

- (void)rollToNext
{
    self.rollIndex++;
    if (self.rollIndex > 7)
    {
        self.rollIndex = 0;
    }
    [self reloadGoodViews];
}

- (void)reloadGoodViews
{
    for (UIView *view in self.luckyGoodViews)
    {
        view.backgroundColor = view.tag == self.rollIndex? [UIColor colorWithHexString:@"c2c2c2"]: UIColor.whiteColor;
    }
}

- (void)historyBtnTapped
{
    RBLuckyDrawHistoryVC *vc = RBLuckyDrawHistoryVC.new;
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark - Setter

#pragma mark - Getter

- (RBNavigationBar *)navigationBar
{
    if (!_navigationBar)
    {
        self.navigationBar = ({
            RBNavigationBar *view = RBNavigationBar.new;
            view.needGradientView = NO;
            [self.view addSubview:view];
            [view mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.right.top.mas_equalTo(0);
                make.height.mas_equalTo(kRBStatusBarHeight + kRBNavigationBarHeight);
            }];
            
            [view.naviBar addBackBtnWithWidth:70 image:[UIImage imageNamed:@"backBlack"]];
            
            UILabel *titleL = [RanTool labelWithFontSize:18 weight:0 color:@"#222222" align:0 text:@"抽奖"];
            [view.naviBar addSubview:titleL];
            [titleL mas_makeConstraints:^(MASConstraintMaker *make) {
                make.center.mas_equalTo(0);
            }];
            
            UIImageView *imgView = [RanTool imgViewWithMode:1 radius:0 imgName:@"luckyDrawRecord"];
            [imgView rbAddTapGesWithTarget:self action:@selector(historyBtnTapped)];
            [imgView extendResponseArea];
            [view.naviBar addSubview:imgView];
            [imgView mas_makeConstraints:^(MASConstraintMaker *make) {
                make.centerY.mas_equalTo(0);
                make.right.mas_equalTo(-Zoom(20));
                make.width.height.mas_equalTo(Zoom(16));
            }];
            
            view;
        });
    }
    return _navigationBar;
}

- (UIScrollView *)scrollView
{
    if (!_scrollView)
    {
        self.scrollView = ({
            UIScrollView *view = UIScrollView.new;
            kRBIgnoreScrollViewInsetsAdjust(view);
            view.showsVerticalScrollIndicator = NO;
            [self.view addSubview:view];
            [view mas_makeConstraints:^(MASConstraintMaker *make) {
                make.top.mas_equalTo(kRBStatusBarHeight + kRBNavigationBarHeight);
                make.left.right.bottom.mas_equalTo(0);
            }];
            view;
        });
    }
    return _scrollView;
}

- (UIView *)goodsItemWithImg: (NSString *)img name: (NSString *)name
{
    UIView *view = UIView.new;
    view.backgroundColor = UIColor.whiteColor;
    [view rbSetCornerRadius:Zoom(9)];
    [view view_addView:[RanTool imgViewWithMode:1 radius:0 imgName:img] withHeight:Zoom(47) width:Zoom(60) top:Zoom(11) bottom:CGFLOAT_MIN left:CGFLOAT_MIN right:CGFLOAT_MIN centerX:YES];
    [view view_addView:[RanTool labelWithFontSize:Zoom(14) weight:1 color:@"#7E3E3F" align:1 text:name] withHeight:CGFLOAT_MIN width:CGFLOAT_MIN top:Zoom(5) bottom:CGFLOAT_MIN left:0 right:0 centerX:0];
    return view;
}

- (NSMutableArray *)luckyGoodViews
{
    if (!_luckyGoodViews)
    {
        self.luckyGoodViews = NSMutableArray.array;
    }
    return _luckyGoodViews;
}

- (RBTimer *)timer
{
    if (!_timer)
    {
        self.timer = RBTimer.new;
    }
    return _timer;
}

@end
